from rest_framework import serializers

from apps.users.models import User, Teacher
from utils import constants
from utils.models import BaseModelSerializer


class UserModelSerializer(BaseModelSerializer):
    fans_count = serializers.IntegerField(read_only=True)
    following_user_count = serializers.IntegerField(read_only=True)
    collection_articles_count = serializers.IntegerField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'decorate_avatar', 'avatar', 'desc', 'birthday', 'type', 'sex', 'mobile',
                  'teacher_id', 'fans_count', 'following_user_count', 'collection_articles_count']
        read_only_fields = ['id', 'mobile', 'decorate_avatar', 'teacher_id']
        extra_kwargs = {
            'username': {'required': False},
            'avatar': {'required': False},
            'desc': {'required': False},
            'birthday': {'required': False},
            'type': {'required': False},
            'sex': {'required': False},
        }

    def validated_avatar(self, value):
        value = value.replace(constants.QINIU_DOMAIN, '')
        return value


class TeacherUserModelSerializer(BaseModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'decorate_avatar', 'mobile', 'sex']
        read_only_fields = ('id', 'decorate_avatar', 'mobile', 'sex')


class TeacherModelSerializer(serializers.ModelSerializer):
    user_id = serializers.IntegerField()
    user = TeacherUserModelSerializer(read_only=True)
    city_id = serializers.IntegerField()
    city = serializers.StringRelatedField()
    province_id = serializers.IntegerField()
    province = serializers.StringRelatedField()
    like_count = serializers.IntegerField(read_only=True)
    rating_avg = serializers.IntegerField(read_only=True)

    class Meta:
        model = Teacher
        fields = '__all__'
        read_only_fields = ('like_users', 'fans')


class UserFansModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'decorate_avatar', 'mobile', 'sex', 'fans']


class UserFollowingTeachersModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        fields = ['id', 'real_name', 'fans']


class UserFollowingsModelSerializer(serializers.ModelSerializer):
    teacher = UserFollowingTeachersModelSerializer()

    class Meta:
        model = User
        fields = ['id', 'username', 'decorate_avatar', 'mobile', 'sex', 'fans', 'teacher']
